package cn.mw.cmdb.util;

import cn.mw.cmdb.entity.sanxia.FileInfo;
import cn.mw.cmdb.entity.sanxia.InputParams;
import cn.mw.microMonitorCommon.entity.autops.AutopsReferencingScriptVariable;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import okhttp3.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author lumingming
 * @createTime 18 10:11
 * @description
 */
public class FilePost {

    public static FileInfo uploadFile(String content, String name,String url,String menuId,String accountId,String userid, String type) throws IOException {


        FileInfo jsonObjectJson =new FileInfo();

        RequestBody fileBody = RequestBody.create(content.getBytes(), MediaType.parse("application/octet-stream"));

        // 创建 multipart 表单
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("menuId", menuId) // 表单字段 menuId
                .addFormDataPart("type", type) // 表单字段 type
                .addFormDataPart("file", name, fileBody); // 文件字段 file，使用字符串内容作为文件内容

        // 构建请求
        Request request = new Request.Builder()
                .url(url)
                .header("accountId", accountId)
                .header("userId", userid)
                .post(multipartBuilder.build())
                .build();

        // 创建 OkHttp 客户端
        OkHttpClient client = new OkHttpClient();


        // 发送请求
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String resp = response.body().string();
                System.out.println("返回参数"+resp);
                JSONObject kmap =  JSON.parseObject(resp);
                JSONObject jsonObject = kmap.getJSONObject("data");
                Gson gson = new Gson();
                jsonObjectJson = gson.fromJson(gson.toJson(jsonObject),FileInfo.class);
            }
        } catch (IOException e) {
            System.out.println("返回参数"+e.toString());
            throw  e;
        }
        return  jsonObjectJson;

    }

    public static JSONObject sendFile(String workflowId,String url,String accountId,String userid,String workOrderId,String destinationPath,List<String> ips, List<FileInfo> fileInfo) throws IOException {

        OkHttpClient client = new OkHttpClient();
        ObjectMapper objectMapper = new ObjectMapper();

        // 创建 RequestBody 对象
        cn.mw.cmdb.entity.sanxia.RequestBody requestBody = createRequestBody(workflowId,workOrderId,destinationPath,ips,fileInfo);

        // 将 RequestBody 转换为 JSON
        String jsonBody = objectMapper.writeValueAsString(requestBody);

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .addHeader("accountId", accountId)
                .addHeader("userid", userid)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(MediaType.parse("application/json"), jsonBody))
                .build();

        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println("Response: " + response.body().string());
            } else {
                System.out.println("Request failed: " + response.code());
            }
        }catch (Exception e){
            System.out.println("Request failed: " + e);
        }
        return null;

    }






    private static cn.mw.cmdb.entity.sanxia.RequestBody createRequestBody(String workflowId,String workOrderId, String destinationPath, List<String> ips, List<FileInfo> fileInfo) {
        cn.mw.cmdb.entity.sanxia.RequestBody body = new cn.mw.cmdb.entity.sanxia.RequestBody();
        body.setWorkflowId(workflowId);
        body.setCallName("DOSM");
        body.setCallbackIdentify("DOSMCALL");
        body.setCallbackParams(Map.of());
        body.setRedundanceParams(Map.of("workOrderId", workOrderId));

        InputParams inputParams = new InputParams();
        inputParams.setFiles(fileInfo);
        inputParams.setAgentList(ips);
        inputParams.setDestinationPath(destinationPath);

        body.setInputParams(inputParams);

        return body;
    }

    public static String content(List<AutopsReferencingScriptVariable> autopsReferencingScriptVariableList, String destinationPath) {
        String res = "UserParameter=";
        if (autopsReferencingScriptVariableList==null||autopsReferencingScriptVariableList.size()==0){
            res=res+"ecs.discovery,"+destinationPath;
        }else {
            res=res+"check_aliyun_ecs[*],"+destinationPath;
            for (AutopsReferencingScriptVariable a:autopsReferencingScriptVariableList) {
                res=res+" "+a.getAutopsReferencingScriptVariableValue();
            }
        }
        return res;
    }
}
